﻿package com.k.demo.util.face;

import java.util.ArrayList;

import org.json.JSONObject;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.baidu.aip.util.Base64Util;

public class FaceUtil {

	public static final String APP_ID = "21412809";
	public static final String API_KEY = "bsNsGPFnMgQRgo2gcnw8WT0S";
	public static final String SECRET_KEY = "bjP8SALnLWbKwLFtFGxcH8SKZzbnymR1";

	private static volatile AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

	public static AipFace getClient() {
		// 可选：设置网络连接参数
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000);
		return client;
	}

	/**
	 * 编码
	 * 
	 * @param form
	 * @return
	 */
	public static String encodeBase64(byte[] form) {
		return Base64Util.encode(form);
	}

	/**
	 * 解码
	 * 
	 * @param data
	 * @return
	 */
	public static byte[] decodeBase64(String data) {
		return Base64Util.decode(data);
	}

	public static boolean faceContrast(String image1, String image2) {
		// image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
		MatchRequest req1 = new MatchRequest(image1, "BASE64");
		MatchRequest req2 = new MatchRequest(image2, "BASE64");
		ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
		requests.add(req1);
		requests.add(req2);

		JSONObject res = client.match(requests);
		System.out.println(res.toString());
		Object object = res.get("result");
		if (object == null || object.toString().equals("null")) {
			return false;
		} else {
			res = (JSONObject) object;
			double result = res.getDouble("score");
			if (result > 90) {
				return true;
			} else {
				return false;
			}
		}
	}

}
